# tpager.py - browse command output with an external pager using temp files
#
# Copyright (C) 2008 David Soria Parra <dsp@php.net>
# Copyright (C) 2010-2012 Eduard-Cristian Stefan <alexandrul.ct@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


"""browse command output with an external pager using temp files

This extension is based on the original Mercurial pager extension,
and uses the same format for the configuration section.

To set the pager that should be used, set the application variable::

  [pager]
  pager = LESS='FSRX' less

On Windows you must define the environment variable LESS = FSRX
using System Properties (Control Panel) and set the pager like::

  [pager]
  pager = c:\\tools\\less.exe

or you could specify the pager options on the same line::

  [pager]
  pager = c:\\tools\\less.exe -FSRX

If no pager is set, the pager extensions uses the environment variable
$PAGER. If neither pager.pager, nor $PAGER is set, no pager is used.

You can enable the pager only for certain commands using
pager.attend. Below is the default list of commands to be paged::

  [pager]
  attend = annotate, cat, diff, export, glog, help, log, qdiff, status, tip

Setting pager.attend to an empty value will disable paging.

For colored output on Mercurial 1.6+ the following options must be set::

  [color]
  mode = ansi

  [pager]
  hg16mode = yes
"""


import os
import subprocess
import sys
import tempfile

from mercurial import dispatch, extensions, util


def uisetup(ui):

    if ui.plain() or '--debugger' in sys.argv or not util.isatty(sys.stdout):
        return

    def pagecmd(orig, ui, options, cmd, cmdfunc):

        pager = ui.config('pager', 'pager', os.environ.get('PAGER'))
        pageroptions = ui.config('pager', 'pageroptions', '')
        hg16mode = ui.config('pager', 'hg16mode', 'YES').upper()

        if not (pager and (cmd in ui.configlist('pager', 'attend', attended))):
            return orig(ui, options, cmd, cmdfunc)

        ui.setconfig('ui', 'formatted', ui.formatted())
        ui.setconfig('ui', 'interactive', False)

        ui.pushbuffer()

        exitcode = orig(ui, options, cmd, cmdfunc)

        if hg16mode == 'YES':
            content = ui.popbuffer(True)
        else:
            content = ui.popbuffer()

        tmpfile = tempfile.NamedTemporaryFile(delete=False).name
        f = open(tmpfile, 'wb')

        for line in content:
            f.write(line)

        f.flush()
        f.close()

        callparams = [pager, tmpfile]
        if pageroptions:
            callparams.insert(1, pageroptions)

        subprocess.Popen(callparams).wait()

        os.remove(tmpfile)

        return exitcode

    extensions.wrapfunction(dispatch, '_runcommand', pagecmd)


attended = ['annotate',
            'branch',
            'branches',
            'bookmarks',
            'cat',
            'diff',
            'diffstat',
            'export',
            'glog',
            'heads',
            'help',
            'log',
            'parents',
            'qdiff',
            'status',
            'summary',
            'tags',
            'tip']
